package com.mycinema.aop;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component //普通类
@Aspect 	//切面
/**
 * 通知类
 * @author Administrator
 *
 */
public class MyAdvice {
	//单独定义切点
	@Pointcut("execution(* com.mycinema..*.*(..))")
	public void pc1(){//通用
		
	}
	
	@Before("pc1()")
	/**
	 * 前置通知
	 * @param jp
	 */
	public void doBefore(JoinPoint jp){
		System.out.println("前置通知");
		System.out.println("方法名："+jp.getSignature());
		
		Object[] args=jp.getArgs();
		System.out.println("king:"+jp.getKind());
		System.out.println("getthis:"+jp.getThis());
		for (Object object : args) {
			System.out.println("参数"+object);
		}
		
		String path="G:\\Y2\\Log\\log.txt";
		File file =new File(path);
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileWriter fWriter=null;
		SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd hh:ss:mm");
		StringBuffer sBuffer =new StringBuffer();
		sBuffer.append("日志时间:"+simpleDateFormat.format(new Date())+"\r\n");
		sBuffer.append("方法名:"+jp.getSignature()+"\r\n");
		try {
			fWriter =new FileWriter(path,true);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		BufferedWriter bWriter =new BufferedWriter(fWriter);
		try {
			
			bWriter.write(sBuffer.toString());
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		try {
			bWriter.flush();
			bWriter.close();
			
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			fWriter.close();
		} catch (IOException e1) {
			
			e1.printStackTrace();
		}
		
	}
	
	/**
	 * 后置通知
	 */
	public void doAfter(){
		System.out.println("后置通知");
	}
	@AfterReturning(value="pc1()",returning="returnVal")
	//返回后
	public void doAfterReturn(Object returnVal){
		System.out.println("返回后通知");
		System.out.println("返回值："+returnVal);
	}
	//环绕通知
	public Object doAround(ProceedingJoinPoint jPoint) throws Throwable{
		System.out.println("开始环绕");
		//调用目标方法
		Object object=jPoint.proceed(jPoint.getArgs());
		System.out.println("结束环绕");
		return object;
	}
	
	//异常后通知
	public void doAfterThrow(Throwable throwable){
		System.out.println("异常后通知");
		System.out.println("错误信息："+throwable.getMessage());
	}
	
}
